package com.scau.eco.service.impl;

import com.scau.eco.dto.*;
import com.scau.eco.entities.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scau.eco.mapper.DataMapper;
import com.scau.eco.service.PageService;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class PageServiceImpl implements PageService{

    @Autowired
    private DataMapper dataMapper;

    /** 页面分割率中 convert_rate 字段 各个 X，Y 坐标值分割符 **/
    private static final String SRPARATOR = "\\|";

    /** 页面分割率中 convert_rate 字段 X，Y 坐标值中的分割符 **/
    private static final String XY_SRPARATOR = "\\=";

    @Override
    public List<SessionAggrStat> getAllSessionAggrStat() {
        return dataMapper.getAllSessionAggrStat();
    }

    @Override
    public SessionAggrStat getSessionAggrStatByTaskId(String taskId) {
        return dataMapper.getSessionAggrStatByTaskId(taskId);
    }

    @Override
    public List<SessionRandomExtract> getRandomExtractByTaskId(String taskId, Integer pageNum, Integer column) {
        return dataMapper.getRandomExtractByTaskId(taskId);
    }

    @Override
    public List<SessionRandomExtract> getAllRandomExtract(Integer pageNum, Integer column) {
        return dataMapper.getAllRandomExtract();
    }

    @Override
    public List<Task> getAllTaskInfo(Integer pageNum, Integer column) {
        return dataMapper.getAllTaskInfo();
    }

    @Override
    public List<Task> getTaskById(String taskId, Integer pageNum, Integer column) {
        return dataMapper.getTaskById(taskId);
    }

    @Override
    public List<CategoryDTO> getTopTenCategory(Integer type) {
        List<CategoryDTO> list = null;
        switch (type){
            case 1:
                list = dataMapper.getTopTenCategoryClickCount();
                break;
            case 2:
                list = dataMapper.getTopTenCategoryOrderCount();
                break;
            case 3:
                list = dataMapper.getTopTenCategoryPayCount();
                break;
        }
        return list;
    }

    @Override
    public List<Top10Session> getTopTenSessionByTaskId(Long categoryid, Integer pageNum, Integer column) {
        return dataMapper.getTopTenSessionByTaskId(categoryid);
    }

    @Override
    public List<Top10Session> getAllTopTenSession(Integer pageNum, Integer column) {
        return dataMapper.getTopTenSession();
    }

    @Override
    public List<PageSplitConvertRateDTO> getPageSplitConvertRate() {
        List<PageSplitConvertRate> convertRateList = dataMapper.getPageSplitConvertRate();
        List<PageSplitConvertRateDTO> dtoList = new ArrayList<>(convertRateList.size());
        for (int i = 0; i < convertRateList.size(); i++) {
            List<PageSplitConvertRateDTO.PageSplitConvertRateXAndY> xAndYList = getList(convertRateList.get(i));
            PageSplitConvertRateDTO temp = new PageSplitConvertRateDTO(convertRateList.get(i).getTaskId(), xAndYList);
            dtoList.add(temp);
        }
        return dtoList;
    }

    @Override
    public AreaTop3ProductDTO getAreaTop3ProductData(String area) {
        List<AreaTop3Product> result =  dataMapper.getAreaTop3ProductData(area);
        // 1. 产品名称+产品id
        List<String> names = result.stream().map((e) -> "产品名称-" + e.getProductName() + " 产品id-" + e.getProductid()).collect(Collectors.toList());
        // 2. 产品点击次数
        List<Integer> values = result.stream().map(AreaTop3Product::getClickCount).collect(Collectors.toList());
        return new AreaTop3ProductDTO(names,values);
    }

    /**
     * 获取用户黑名单
     * @return
     */
    @Override
    public List<BlackUser> getBlackUserData(Integer pageNum, Integer column) {
        List<BlackUser> result = dataMapper.getBlackUserData();
        // 填充数据
        List<Integer> list = new ArrayList<>();
        list.add(203);list.add(194);list.add(185);list.add(150);
        for (int i = 0; i < list.size();i++) {
            result.get(i).setClickTime(list.get(i));
        }
        return result;
    }

    /**
     * 获取每天每个省份Top3热门广告
     * @param pageNum
     * @param column
     * @return
     */
    @Override
    public List<ProvinceTop3Ad> getProvinceTop3AdData(String province,Integer pageNum, Integer column) {
        if(province == null) return dataMapper.getAllProvinceTop3AdData();
        return dataMapper.getProvinceTop3AdData(province);
    }

    /**
     * 根据一个页面分割率实体获取其中的 X，Y 坐标，并对X坐标进行字典序排序
     * @param convertRate
     * @return
     */
    private List<PageSplitConvertRateDTO.PageSplitConvertRateXAndY> getList(PageSplitConvertRate convertRate){
        String params = convertRate.getConvertRate();
        String[] xyList = params.split(SRPARATOR);
        List<PageSplitConvertRateDTO.PageSplitConvertRateXAndY> result = new ArrayList<>(xyList.length);
        for (int i = 0; i < xyList.length; i++) {
            String[] xAndY = xyList[i].split(XY_SRPARATOR);
            PageSplitConvertRateDTO.PageSplitConvertRateXAndY temp = new PageSplitConvertRateDTO.PageSplitConvertRateXAndY(xAndY[0], xAndY[1]);
            result.add(temp);
        }

        Collections.sort(result, new Comparator<PageSplitConvertRateDTO.PageSplitConvertRateXAndY>() {
            @Override
            public int compare(PageSplitConvertRateDTO.PageSplitConvertRateXAndY o1, PageSplitConvertRateDTO.PageSplitConvertRateXAndY o2) {
                return o1.getX().compareTo(o2.getX());
            }
        });
        return result;
    }

        /**
         * 最近一小时广告点击量实时统计
         * @return
         */
    @Override
    public List<AdClickTrend> getAdClickTrend() {
        return dataMapper.getAdClickTrendByGroup();
    }

    @Override
    public AdClickTrendDTO getAdClickTrendByGroup() {
        // 1. 获取当前广告的所有id
        List<String> allAdId = dataMapper.getAllAdId();
        // 2. 获取当前的所有时间段
        List<String> allTimeInterval = dataMapper.getAllTimeInterval().subList(0,10);
        // 3. 获取一个entry列表
        List<AdClickTrend> result = dataMapper.getAdClickTrendByGroupTimeAndId();
        Map<String, List<Integer>> map = result.stream().collect(
                Collectors.groupingBy(AdClickTrend::getAdid,
                        Collectors.mapping(AdClickTrend::getClickCount, Collectors.toList())));
        // 转化为entry
        List<AdClickTrendSeriesDTO> adClickTrendSeriesDTOS = new ArrayList<>(map.size());
        for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
            AdClickTrendSeriesDTO target = AdClickTrendSeriesDTO.builder()
                    .name(entry.getKey())
                    .data(entry.getValue())
                    .smooth(Boolean.TRUE)
                    .type("line")
                    .build();
            adClickTrendSeriesDTOS.add(target);
        }

        return AdClickTrendDTO.builder()
                .idSet(allAdId)
                .timeInterval(allTimeInterval)
                .seriesDTOS(adClickTrendSeriesDTOS).build();
    }

    @Override
    public List<AdStat> getAdStatData(String province, String city) {
        return dataMapper.getAdStatData(province,city);
    }

    @Override
    public List<CategoryAllDTO> getAllTopTenCategory() {
        return dataMapper.getTopTenCategoryAll();
    }

}
